package com.lesports.qmt.play.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: liruidong
 * @date: 2016-03-09 17:14
 * @Description: http post/get 请求调用实现
 * @version: V1.0
 */

public class HttpUtil {

    private static Logger logger =Logger.getLogger(HttpUtil.class);

    /**
     *  http get 调用接口
     * @param url 请求的地址
     * @return
     */
    public static String sendGetHttpContent(String url,Header[] headers) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpGet method = new HttpGet(url);
            method.setHeaders(headers);
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            }
        } catch (Exception e) {
            logger.error("接口调用异常", e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                logger.error("接口调用异常", e);
            }
        }
        return responseText;
    }

    /**
     * POST请求调用接口
     * @param url 请求地址
     * @param paramsMap 参数
     * @param headers 请求头
     * @return
     */
    public static String sendPostHttpContent(String url, Map<String, Object> paramsMap, Header[] headers, String strParam){
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, Object> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue()));
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
            }
            if (!StringUtils.isEmpty(strParam)){
                method.setEntity(new StringEntity(strParam,"UTF-8"));
            }
            if (headers != null && headers.length > 0){
                method.setHeaders(headers);
            }
            method.setHeaders(headers);
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity,Charset.forName("UTF-8"));
            }
        } catch (Exception e) {
            logger.error("接口调用异常", e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                logger.error("接口调用异常", e);
            }
        }
        return responseText;
    }

    /**
     * delete请求调用接口
     * @param url
     * @return
     */
    public static Map<String,String> sendDeleteHttpContent(String url){
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        String statusCode = "";
        Map<String,String> responseMap = new HashMap<>();
        CloseableHttpResponse response = null;
        try {
            HttpDelete method = new HttpDelete(url);
            response = client.execute(method);
            statusCode = String.valueOf(response.getStatusLine().getStatusCode());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            logger.error("接口调用异常", e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                logger.error("接口调用异常", e);
            }
        }
        responseMap.put("statusCode",statusCode);
        responseMap.put("responseText",responseText);
        return responseMap;
    }

    /**
     * put 请求接口
     * @param url
     * @param reqParams
     * @param headers
     * @return
     */
    public static String sendPutHttpContent(String url, String reqParams, Header[] headers){
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;

        try {
            HttpPut method = new HttpPut(url);
            if (!StringUtils.isEmpty(reqParams)){
                method.setEntity(new StringEntity(reqParams,"UTF-8"));
            }
            if (headers != null && headers.length > 0){
                method.setHeaders(headers);
            }
            method.setHeaders(headers);
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            logger.error("接口调用异常", e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                logger.error("接口调用异常", e);
            }
        }
        return responseText;

    }


    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}